package com.qujia.station.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.util.StringUtil;
import com.google.gson.Gson;
import com.qujia.common.constant.Constants;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.DateUtils;
import com.qujia.station.domain.StationDeviceManage;
import com.qujia.station.domain.dto.StationDeviceManageDTO;
import com.qujia.station.mapper.StationDeviceManageMapper;
import com.qujia.station.service.IStationDeviceManageService;
import com.qujia.station.service.StationDeviceAudioService;
import com.qujia.station.utils.Methods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 油站设备管理Service业务层处理
 * 
 * @author qujia
 * @date 2021-01-13
 */
@Service
@Slf4j
public class StationDeviceManageServiceImpl implements IStationDeviceManageService 
{
    @Autowired
    private StationDeviceManageMapper stationDeviceManageMapper;

    @Autowired
    private RedisCache redisCache;

    @Resource
    private StationDeviceAudioService stationDeviceAudioService;

    /**
     * 查询油站设备管理
     * 
     * @param deviceId 油站设备管理ID
     * @return 油站设备管理
     */
    @Override
    public StationDeviceManage selectStationDeviceManageById(Long deviceId)
    {
        return stationDeviceManageMapper.selectStationDeviceManageById(deviceId);
    }

    /**
     * 查询油站设备管理列表
     * 
     * @param stationDeviceManage 油站设备管理
     * @return 油站设备管理
     */
    @Override
    public List<StationDeviceManage> selectStationDeviceManageList(StationDeviceManage stationDeviceManage)
    {
        return stationDeviceManageMapper.selectStationDeviceManageList(stationDeviceManage);
    }

    /**
     * 新增油站设备管理
     * 
     * @param stationDeviceManage 油站设备管理
     * @return 结果
     */
    @Override
    public int insertStationDeviceManage(StationDeviceManage stationDeviceManage) throws Exception {
        //如果是易联云小票机 需要生成access_token
        Methods m= Methods.getInstance();
        m.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
        if(StringUtil.isEmpty(stationDeviceManage.getAccessToken()) && "1".equals(stationDeviceManage.getDeviceFactory()) && "3".equals(stationDeviceManage.getDeviceType())){

            String freedomToken = m.getFreedomToken();
//            JSONObject json = new JSONObject(freedomToken);
//            if (!"0".equals(json.getString("error"))) {
//                throw new Exception(json.getString("error_description"));
//            }
//            if(!"0".equals(json.getJSONObject("error"))){
//                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
//            }
//            JSONObject body = json.getJSONObject("body");
//            String token = body.getString("access_token");
            redisCache.setCacheObject(Constants.DEVICE_CLIENT_TOKEN + stationDeviceManage.getClientId(),freedomToken,30, TimeUnit.DAYS);
        }
        //判断状态

        if("3".equals(stationDeviceManage.getDeviceFactory())){
            checkStatus(stationDeviceManage,m);

            stationDeviceAudioService.setVoice(stationDeviceManage,m);

        }


        stationDeviceManage.setCreateTime(DateUtils.getNowDate());
        return stationDeviceManageMapper.insertStationDeviceManage(stationDeviceManage);
    }

    @Override
    public int insertStationDeviceManage(StationDeviceManageDTO stationDeviceManageDTO) {
        Long count = stationDeviceManageMapper.selectStationDeviceNo(stationDeviceManageDTO.getDeviceNo());
        if (null != count && count>0) {
            throw new CustomException("该设备已录入");
        }
        StationDeviceManage stationDeviceManage = BeanUtil.copyProperties(stationDeviceManageDTO, StationDeviceManage.class);
        stationDeviceManage.setCreateTime(DateUtils.getNowDate());
        return stationDeviceManageMapper.insertStationDeviceManage(stationDeviceManage);
    }

    @Override
    public void checkStatus(StationDeviceManage stationDeviceManage,Methods m){
        m.getFreedomToken();
        String printStatus = m.getPrintStatus(stationDeviceManage.getDeviceNo());
        log.info("打印机状态{}",printStatus);

        Gson gson = new Gson();
        HashMap<Object, Object> map = new HashMap<>();

        Map mapRes = gson.fromJson(printStatus, Map.class);
        Map body =  (Map)mapRes.get("body");
        if(Objects.isNull(body)){
            throw new CustomException("请检查小票机信息是否正确");
        }
        String state = body.get("state").toString();
        if(!"1".equals(state)){
            throw new CustomException("小票机不在线");
        }

    }

    /**
     * 修改油站设备管理
     * 
     * @param stationDeviceManage 油站设备管理
     * @return 结果
     */
//    @CacheEvict(value = { "PosMachineServiceImpl_getStationDeviceManager"},
//            key="'d_'+#root.args[0].getDeviceNo()",
//            condition = "#root.args[0] != null"
//    )
    @Override
    public int updateStationDeviceManage(StationDeviceManage stationDeviceManage)
    {
        StationDeviceManage old = stationDeviceManageMapper.selectStationDeviceManageById(stationDeviceManage.getDeviceId());
        if (old == null) {
            return 0;
        }
        stationDeviceManage.setUpdateTime(DateUtils.getNowDate());
        int i = stationDeviceManageMapper.updateStationDeviceManage(stationDeviceManage);
        redisCache.deleteObject(String.format("PosMachineServiceImpl_getStationDeviceManager::s_%sd_%s",old.getStationId(),old.getDeviceNo()));
        return i;
    }

    @Override
    public int updateStationDeviceManage(StationDeviceManageDTO stationDeviceManageDTO) {
        StationDeviceManage old = stationDeviceManageMapper.selectStationDeviceManageById(stationDeviceManageDTO.getDeviceId());
        if (old == null) {
            throw new CustomException("该设备不存在");
        }
        StationDeviceManage stationDeviceManage = BeanUtil.copyProperties(stationDeviceManageDTO, StationDeviceManage.class);
        stationDeviceManage.setUpdateTime(DateUtils.getNowDate());
        int i = stationDeviceManageMapper.updateStationDeviceManage(stationDeviceManage);
        return i;
    }

    /**
     * 批量删除油站设备管理
     * 
     * @param deviceIds 需要删除的油站设备管理ID
     * @return 结果
     */
    @Override
    public int deleteStationDeviceManageByIds(Long[] deviceIds)
    {
        return stationDeviceManageMapper.deleteStationDeviceManageByIds(deviceIds);
    }

    /**
     * 删除油站设备管理信息
     * 
     * @param deviceId 油站设备管理ID
     * @return 结果
     */
    @Override
    public int deleteStationDeviceManageById(Long deviceId)
    {
        return stationDeviceManageMapper.deleteStationDeviceManageById(deviceId);
    }

    @Override
    public Map<String, Object> getPrinterSnByStationId(Map<String, Object> params) {
        return stationDeviceManageMapper.getPrinterSnByStationId(params);
    }
}
